import React,{useEffect} from 'react';
import {Button,Form,Input,message} from 'antd';
import {LockOutlined,UserOutlined} from '@ant-design/icons';
import {useNavigate} from 'react-router-dom';

import logo from '../../assets/logo.png';
import './index.less';
import {reqLogin} from '../../api';
import memoryUtils from '../../utils/memoryUtils';
import {savaUser} from '../../utils/storageUtils';

/**
 * 一级组件 主页
 */
function Login(){
  // navigate跳转路由
  const navigate = useNavigate();
  // 从内存中获取用户信息
  const user = memoryUtils.user;

  /**
   * 页面刷新时调用
   * 判断是否登录，如果已登录则跳转到主页
   */
  useEffect(function(){
    if(user && user._id){
      navigate('/',{replace: true});
    }
  });

  /**
   * 提交Form表单方法
   * @param values
   */
  async function onFinish(values){
    // 取出表单数据
    const {username,password} = values;
    // 调用登录方法 reqLogin
    const response = await reqLogin(username,password);
    if(response.status === 0){
      message.success("登录成功！");
      //登陆成功 跳转到首页，并且带对象参数 replace格式跳转
      navigate('/',{replace: true});
      // 缓存用户信息到内存中
      memoryUtils.user = response.data;
      savaUser(response.data);
    }else{
      // 登陆失败
      message.error("账号或者密码错误！");
    }
  }

  return (
    <div className="login">
      <header className="login-header">
        <img src={logo} alt="logo"/>
        <h1>React项目：谷粒后台</h1>
      </header>
      <section className="login-section">
        <h2>用户登录</h2>
        {/*form表单*/}
        <Form
          name="login-form"
          className="login-form"
          onFinish={onFinish}
          //根据name展示默认值
          initialValues={{
            username: "admin",
            password: "admin",
          }}
        >
          {/*username 用户名*/}
          <Form.Item
            name="username"
            rules={[
              {required: true,whitespace: true, message: "用户名不能为空!" },
              {max: 12, message: "用户名不能大于12位!" },
              {min: 4, message: "用户名不能小于4位!" },
              {pattern: /^\w+$/, message: "用户名必须由英文、数字或下划线组成!" },
            ]}
          >
            <Input prefix={<UserOutlined className="site-form-item-icon" style={{color: '#d9d9d9'}} />} placeholder="username" />
          </Form.Item>
          {/*password 密码*/}
          <Form.Item
            name="password"
            rules={[
              {required: true,whitespace: true, message: "密码不能为空!" },
              {max: 12, message: "密码不能大于12位!" },
              {min: 4, message: "密码名不能小于4位!" },
              {pattern: /^\w+$/, message: "密码必须由英文、数字或下划线组成!" }
            ]}
          >
            <Input prefix={<LockOutlined className="site-form-item-icon" style={{color: '#d9d9d9'}} />} type="password" placeholder="password"/>
          </Form.Item>
          {/*登录按钮*/}
          <Form.Item>
            <Button type="primary" htmlType="submit" className="login-form-button">
              登 录
            </Button>
          </Form.Item>
        </Form>
      </section>
    </div>
  );
}

export default Login;